package com.treasure.mall.biz.entity.live;

import com.treasure.mall.biz.entity.BasePO;
import com.treasure.mall.biz.entity.embeddable.LiveRoomData;
import com.treasure.mall.biz.entity.user.MerchantPO;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.live.LiveEnums;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.OrderBy;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

/**
 *
 * 直播间信息
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.entity.live
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/11 18:30
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.biz.entity.live Inc. All rights reserved.
 */
@Entity
@Getter
@Setter
@Table(name = "zb_live_room")
@NoArgsConstructor
@Cacheable(false)
public class LiveRoomPO extends BasePO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    /**
     * 所属商家
     */
    @ManyToOne
    @JoinColumn(name = "merchant_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private MerchantPO merchant;
    /**
     * 直播间数据
     */
    private LiveRoomData data;
    /**
     * 预告时间
     */
    @Column(name = "time_herald", columnDefinition = Constant.DATE_COLUMN_DEFINITION)
    private LocalDateTime timeHerald;

    /**
     * 排序
     * 数字越大越靠前
     */
    @Column(name = "order_weight")
    private Integer orderWeight = 0;

    /**
     * 直播间是否开始直播中
     */
    @Column(name = "live_playing")
    private Integer livePlaying = 0;

    /**
     * 默认服务费比例，百分比
     * 不会允许商户修改该
     */
    @Column(name = "reward_rate", scale = 3, precision = 6)
    private BigDecimal rewardRate = BigDecimal.valueOf(15);
    /**
     * 一级返佣百分比
     */
    @Column(name = "rebate_rate_one", scale = 3, precision = 6)
    private BigDecimal rebateRateOne;
    /**
     * 二级返佣百分比
     */
    @Column(name = "rebate_rate_two", scale = 3, precision = 6)
    private BigDecimal rebateRateTwo;
    /**
     * 被允许使用
     */
    @Column(name = "is_enabled")
    private boolean enabled = true;

    /**
     * 是否是平台直播间
     */
    @Column(name = "is_platform")
    private boolean platform = false;

    /**
     * 是否推荐
     */
    @Column(name = "is_recommend")
    private boolean recommendFlag = false;

    /**
     * 推荐背景颜色
     */
    @Column(name = "background_color")
    private String backgroundColor;
    /**
     * 推荐图片
     */
    @Column(name = "background_image")
    private String backgroundImage;


    /**
     * 审核状态{@link LiveEnums.AuditStatus}
     */
    @Column(name = "audit")
    private LiveEnums.AuditStatus auditStatus;
    /**
     * 开通时间
     */
    @Column(name = "open_time", columnDefinition = Constant.DATE_COLUMN_DEFINITION)
    private LocalDateTime openTime;
    /**
     * 理由
     */
    @Column(length = 100, name = "approval_message")
    private String reason;
    @OneToMany(mappedBy = "liveRoomPO", fetch = FetchType.EAGER)
    @Where(clause = "play_status=1 or play_status=0")
    @OrderBy(clause = "start_time desc")
    private List<LiveSessionPO> liveSessionPOS;

    /**
     * 公告内容
     */
    @Column(name = "notice", length = 200)
    private String notice;

    /**
     * 启用广告
     */
    @Column(name = "enable_notice")
    private boolean enableNotice;

    /**
     * @return 返回流地址toStreamName
     */
    public String toStreamName() {
        return MessageFormat.format("staging-room-{0}", id);
    }

    /**
     * 是否直播中
     *
     * @return
     */
    public boolean isPlaying() {
        return liveSessionPOS.stream().anyMatch(p -> p.getPlayStatus() == LiveEnums.PlayStatus.PAYING);
    }

    /**
     * 是否开启直播
     *
     * @return
     */
    public boolean isEnableRobot() {
        return liveSessionPOS.stream().anyMatch(p -> {
                    if (p.getEnableRobot() != null) {
                        return p.getEnableRobot();
                    }
                    return false;
                }
        );
    }

    /**
     * @return
     */
    public String getSessionId() {
        if (liveSessionPOS != null && liveSessionPOS.size() > 0) {
            return liveSessionPOS.get(0).getId();
        }
        return null;
    }

    public LiveRoomPO(Long id) {
        this.id = id;
    }

    /**
     * 得到当前的场次
     *
     * @return
     */
    public LiveSessionPO currentSession() {
        if (this.liveSessionPOS.size() > 0) {
            LiveSessionPO currentSession = this.liveSessionPOS
                    .stream()
                    .filter(p -> p.getPlayStatus() == LiveEnums.PlayStatus.PAYING)
                    .findAny().orElse(null);
            if (currentSession == null) {
                //说明是预告中的,得到最近的一场预告
                currentSession = this.liveSessionPOS
                        .stream()
                        .filter(p -> p.getPlayStatus() == LiveEnums.PlayStatus.TO_PLAY)
                        .min(Comparator.comparing(LiveSessionPO::getForeshowTime)).orElse(null);
            }
            return currentSession;
        }
        return null;
    }
}
